package com.ufo.store.management.ui.fragment;


import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.ufo.store.management.R;
import com.ufo.store.management.adapter.CameraSimpleRecyclerAdapter;
import com.ufo.store.management.entity.ServiceResult;
import com.ufo.store.management.entity.YSUser;
import com.ufo.store.management.net.NetCallback;
import com.ufo.store.management.net.NetHelper;
import com.videogo.constant.IntentConsts;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.bean.EZCameraInfo;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.videogo.ui.realplay.EZRealPlayActivity;
import com.videogo.util.ConnectionDetector;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by taoli on 2018/5/22.
 */

public class YSVideoFragment extends BaseLazyFragment {
    public static final String TAG = YSVideoFragment.class.getSimpleName();
    private final int NOTIFICATION_OAUTH_SUCCESS = 101;
    private final int NOTIFICATION_OAUTH_FAIL = 102;
    private static final int LOAD_DATA_FINISH = 103;
    private static final int REFRESH_DATA_FINISH = 104;

    private EZOpenSDK mEZOpenSDK = null;
    private Map<EZDeviceInfo, List<EZCameraInfo>> mDeviceMap = new HashMap<EZDeviceInfo, List<EZCameraInfo>>();
    private List<EZCameraInfo> mCameraInfoList = new ArrayList<EZCameraInfo>();

    private RecyclerView mCameraRecyclerView = null;
    private CameraSimpleRecyclerAdapter mCameraSimpleRecyclerAdapter = null;

    private final Handler viewHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case NOTIFICATION_OAUTH_SUCCESS:
                    getCameraInfoList(true);
                    break;
                case NOTIFICATION_OAUTH_FAIL:
                    break;
                case REFRESH_DATA_FINISH:
                    setCameraList();
                    break;
                case LOAD_DATA_FINISH:
                    setCameraList();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    /**
     * 布局文件ID
     *
     * @return
     */
    protected int getLayoutId() {
        return R.layout.fragment_ysvideo;
    }

    /**
     * 初始化组件
     */
    protected void initViewData(View entryView) {
        mCameraRecyclerView = (RecyclerView) entryView.findViewById(R.id.recyclerview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mCameraRecyclerView.setLayoutManager(linearLayoutManager);
        mCameraSimpleRecyclerAdapter = new CameraSimpleRecyclerAdapter(getActivity(), mCameraInfoList);
        mCameraRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mCameraRecyclerView.setHasFixedSize(true);
        mCameraRecyclerView.setAdapter(mCameraSimpleRecyclerAdapter);
        mCameraSimpleRecyclerAdapter.setOnClickListener(new CameraSimpleRecyclerAdapter.OnClickListener() {
            @Override
            public void onPlayClick(View v, int position) {
                EZCameraInfo ezCameraInfo = mCameraSimpleRecyclerAdapter.getItem(position);
                EZDeviceInfo deviceInfo = null;
                for (Map.Entry<EZDeviceInfo, List<EZCameraInfo>> entry : mDeviceMap.entrySet()) {
                    EZDeviceInfo device = entry.getKey();
                    if (device.getDeviceSerial().equals(ezCameraInfo.getDeviceSerial())) {
                        deviceInfo = device;
                        break;
                    }
                }
                Intent intent = new Intent(getActivity(), EZRealPlayActivity.class);
                intent.putExtra(IntentConsts.EXTRA_CAMERA_INFO, ezCameraInfo);
                intent.putExtra(IntentConsts.EXTRA_DEVICE_INFO, deviceInfo);
                startActivity(intent);
            }
        });
    }

    /**
     * 初始化数据
     */
    protected void initData() {
        loaded();
        mEZOpenSDK = EZOpenSDK.getInstance();
    }

    protected void onFirstUserVisible() {
        loginEzviz();
    }

    protected void onUserVisible() {

    }

    protected void onFirstUserInvisible() {

    }

    protected void onUserInvisible() {

    }

    private void loginEzviz() {
        NetHelper.getYSUser(getActivity(), new NetCallback<ServiceResult>() {
            @Override
            public void onSucceed(int code) {

            }

            @Override
            public void onSucceed(ServiceResult rspData) {
                YSUser mUser = (YSUser) rspData;
                String accessToken = mUser.result.data.accessToken;
                mEZOpenSDK.setAccessToken(accessToken);
                Message _Msg = viewHandler.obtainMessage(NOTIFICATION_OAUTH_SUCCESS, 0);
                viewHandler.sendMessage(_Msg);
            }

            @Override
            public void onFailed(String msg) {
                Message _Msg = viewHandler.obtainMessage(NOTIFICATION_OAUTH_FAIL, 0);
                viewHandler.sendMessage(_Msg);
            }
        }, YSUser.class);
    }


    private void getCameraInfoList(boolean headerOrFooter) {
        if (getActivity().isFinishing()) {
            return;
        }
        mDeviceMap.clear();
        mCameraInfoList.clear();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!ConnectionDetector.isNetworkAvailable(getActivity().getApplicationContext())) {
                    return;
                }
                try {
                    List<EZDeviceInfo> deviceList = mEZOpenSDK.getDeviceList(0, 20);
                    for (EZDeviceInfo deviceInfo : deviceList) {
                        List<EZCameraInfo> cameraList = deviceInfo.getCameraInfoList();
                        mDeviceMap.put(deviceInfo, cameraList);
                        mCameraInfoList.addAll(cameraList);
                    }

                    if (mCameraInfoList != null && mCameraInfoList.size() != 0) {
                        Message _Msg = viewHandler.obtainMessage(REFRESH_DATA_FINISH, 0);
                        viewHandler.sendMessage(_Msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void setCameraList() {
        mCameraSimpleRecyclerAdapter.notifyDataSetChanged();
    }
}
